package com.hu.service.impl;

import com.hu.entity.dto.UserRegisterDTO;
import com.hu.entity.pojo.UserEntity;
import com.hu.mapper.UserMapper;
import com.hu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 用户注册
     * @param userRegisterDTO
     */
    public void register(UserRegisterDTO userRegisterDTO) {
        userMapper.insertUser(userRegisterDTO);
    }

    /**
     * 用户登录
     * @param userRegisterDTO
     */
    @Override
    public UserEntity login(UserRegisterDTO userRegisterDTO) {
        if(userRegisterDTO.getPhone() != null && userRegisterDTO.getPassword() != null ){
            // 用户是手机号密码登录
            UserEntity userEntity = userMapper.selectByPhoneAndPassword(userRegisterDTO);
            return userEntity;
        }
        if(userRegisterDTO.getPhone() != null && userRegisterDTO.getCode() != null){
            // 用户是手机号验证码登录
            String phone = userRegisterDTO.getPhone();
            String inputCode = userRegisterDTO.getCode();
            String cacheCode = stringRedisTemplate.opsForValue().get("login:" + phone);
            if(inputCode.equals(cacheCode)){
                UserEntity userEntity = userMapper.selectByPhone(userRegisterDTO);
                return userEntity;
            }
        }
        return null;
    }

    /**
     * 严重手机号是否已注册
     * @param userRegisterDTO
     * @return
     */
    public UserEntity selectByPhone(UserRegisterDTO userRegisterDTO) {
        UserEntity userEntity = userMapper.selectByPhone(userRegisterDTO);
        return userEntity;
    }

    /**
     * 修改用户信息
     * @param userEntity
     */
    public void updateById(UserEntity userEntity) {
        userMapper.updateUserInfoById(userEntity);
    }
}
